package pl.polidea.imf.blackberry.service.statemachine;

import microlog.net.sf.microlog.core.Logger;
import microlog.net.sf.microlog.core.LoggerFactory;
import pl.polidea.imf.blackberry.service.IMFService;
import pl.polidea.imf.blackberry.util.Settings;
import pl.polidea.imf.common.java.http.requests.ServerCommunicationError;
import pl.polidea.imf.common.java.model.LoginReq;
import pl.polidea.imf.common.java.model.LoginResp;
import pl.polidea.imf.common.java.model.LogoutReq;
import pl.polidea.imf.common.java.model.LogoutResp;
import pl.polidea.imf.common.java.net.CommunicationManager;

public class StateLogin extends State {
	
	static Logger logger = LoggerFactory.getLogger(StateLogin.class);
	
	public static final int SUB_STATE_LOGIN_INIT = 0;
	public static final int SUB_STATE_LOGIN_LOGIN = 1;
	public static final int SUB_STATE_LOGIN_LOGOUT= 2;
	public static final int SUB_STATE_LOGIN_FAILED= 3;

	public StateLogin(int subState) {
		super(subState);
		
	}

	public State doWork() {
		State nextState = null;
		CommunicationManager communicationManager = IMFService.getInstance().getCommunicationManager();
		switch (getSubState()) {
			case SUB_STATE_LOGIN_LOGIN:
				Settings settings = Settings.getInstance();
				String regKey = (String)settings.getField(Settings.KEY_REG_KEY);
								
				try {
					LoginResp resp = communicationManager.login(new LoginReq(regKey, System.currentTimeMillis()));
					IMFService.getInstance().setSession(resp.getSession());
					nextState = new StateOnline(StateOnline.SUB_STATE_ONLINE_ACTIVE);
				} catch (ServerCommunicationError e) {
					logger.debug("Cannot login: " + e.toString());
					nextState = new StateLogin(SUB_STATE_LOGIN_FAILED);
				}
				break;
			case SUB_STATE_LOGIN_LOGOUT:
				
				try {
					
					LogoutResp resp = communicationManager.logout(new LogoutReq(IMFService.getInstance().getSessionKey(), System.currentTimeMillis()));
					nextState = new StateOffLine(StateOffLine.SUB_STATE_OFFLINE);
				} catch (ServerCommunicationError e) {
					logger.debug("Cannot logout: " + e.toString());
					nextState = new StateOffLine(StateOffLine.SUB_STATE_OFFLINE);
				}
				break;
			case SUB_STATE_LOGIN_FAILED:
				nextState = new StateOffLine(StateOffLine.SUB_STATE_OFFLINE);
				break;

			default:
				break;
		}
		
		return nextState;
	}
	
	

}
